<template>
    <view class="bg-[#F6F6F6] min-h-screen">
        <up-navbar :safeAreaInsetTop="true" bgColor="#FFF" :placeholder="true">
            <template #left>
                <view class="flex px-[24rpx] py-[16rpx] border-[1rpx] border-slate-200 rounded-[38rpx]">
                    <up-icon name="arrow-left" size="19" @click="goback"></up-icon>
                    <up-line direction="column" :hairline="false" length="16" margin="0 8px"></up-line>
                    <up-icon name="home" size="20" @click="gohome"></up-icon>
                </view>
            </template>
        </up-navbar>
        <view class="">
            <view class="bg-[#FFF] flex justify-evenly p-[20rpx]  mt-[20rpx] mx-[20rpx] rounded-t-[16rpx]">
                <view @click="CheckTabA(0)" :class="current == 0 ? 'bg-[#DAEDFF] border-[#DAEDFF]':''" class="w-[300rpx] text-center py-[20rpx] rounded-[16rpx] border-[1rpx] border-[#ddd] font-normal text-[32rpx] text-[#333]">配送信息</view>
                <view @click="CheckTabA(1)" :class="current == 1 ? 'bg-[#DAEDFF] border-[#DAEDFF]':''" class="w-[300rpx] text-center py-[20rpx] rounded-[16rpx] border-[1rpx] border-[#ddd] font-normal text-[32rpx] text-[#333]">自提信息</view>
            </view>
            <view v-if="!current" class="mx-[20rpx] border-[fff] bg-[#FFF] px-[30rpx]  flex relative "
                :class="value == index ? 'active' : ''" @click="checkItem(index)">
                <view class="w-[446rpx] pr-[44rpx]">
                    <view class="text-[26rpx] text-[#333] font-bold mb-[20rpx]">{{ Detail.appStore?.name }}</view>
                    <view class="flex items-center mb-[20rpx]">
                        <image src="../static/haddress.png" mode="scaleToFill"
                            class="w-[20rpx] h-[20rpx] block shrink-0  mr-[4rpx]" />
                        <view class="text-[22rpx] text-[#999] font-normal tracking-[1rpx]">{{ Detail.appStore?.address }}
                        </view>
                    </view>
                    <view class="flex items-center">
                        <image src="../static/htime.png" mode="scaleToFill"
                            class="w-[20rpx] h-[20rpx] block shrink-0 mr-[4rpx]" />
                        <view class="text-[22rpx] text-[#999] font-normal tracking-[1rpx]">营业时间：{{
                            Detail.appStore?.businessHours
                            }}</view>
                    </view>
                </view>
                <up-line direction="column" :hairline="false" length="182rpx" margin=""></up-line>
                <view class="flex flex-col items-center justify-center flex-1">
                    <view class="text-[22rpx] text-[#46A7FD] mb-[8rpx]">进店选购</view>
                    <view class="text-[20rpx] text-[#999] font-normal leading-[36rpx] ">
                        距离{{ (Detail.distance / 1000).toFixed(2) }}km</view>
                    <view class="flex items-center mt-[16rpx]">
                        <image @click="callPhone" src="../static/bphone.png" mode="scaleToFill"
                            class="w-[36rpx] h-[36rpx] block mr-[32rpx]" />
                        <image @click="daohang" src="../static/baddress.png" mode="scaleToFill"
                            class="w-[36rpx] h-[36rpx] block" />
                    </view>
                </view>
            </view>
            <view v-else class="px-[20rpx] pt-[20rpx] mx-[20rpx] bg-[#fff] ">
            <view class="addressBox flex items-center justify-between" @click="getAddress">
                <view class="" v-if="Detail.addressId">
                    <view class="flex items-center mb-[16rpx]">
                        <view class="tab mr-[8rpx]">默认</view>
                        <view class="text-[30rpx] text-[#333] font-bold">{{ Detail.province }} {{ Detail.city }} {{
                            Detail.area
                            }}</view>
                    </view>
                    <view class="text-[30rpx] text-[#333] font-bold mb-[24rpx]">{{ Detail.address }}</view>
                    <view class="flex items-center">
                        <view class="text-[24rpx] text-[#666] font-normal mr-[16rpx]">{{ Detail.receiveName }}</view>
                        <view class="text-[24rpx] text-[#666] font-normal">{{ Detail.mobile }}</view>
                    </view>
                </view>
                <view v-else class="text-[30rpx] text-[#666] font-normal">请选择地址</view>
                <image src="../static/right.png" mode="scaleToFill" class="w-[32rpx] h-[32rpx] block" />
            </view>
            </view>
            <view class="mx-[20rpx] flex items-center justify-between bg-[#fff] p-[20rpx] rounded-b-[16rpx]">
                <view @click="checkType(item,index)" class="w-[218rpx] text-center box-border h-[64rpx] leading-[62rpx] text-[30rpx] text-[#333] font-normal rounded-[16rpx] border-[1rpx] border-[#999]" :class="[item.check ? 'bg-[#DAEDFF] text-[#46A7FD] border-[#A2D3FE]' : '',item.disable ? 'bg-[#F5F5F5] text-[#CCCCCC] border-[#E5E5E5]':'']" v-for="(item,index) in distributionList" :key="index">{{ item.name }}</view>
            </view>
        </view>
        <view class="m-[20rpx] p-[32rpx] bg-[#FFF] rounded-[16rpx]">
            <view class="flex mb-[20rpx]" v-for="(item, index) in Detail?.carVoList" :key="index">
                <view class="mr-[24rpx] w-[176rpx] h-[176rpx]">
                    <image :src="item.pic" class="w-[100%] h-[100%] rounded-[8rpx]" mode="scaleToFill" />
                </view>
                <view class="flex-1">
                    <view class="text-[30rpx] text-[#111] font-normal mb-[4rpx]">{{ item.goodName }}</view>
                    <view class="text-[24rpx] text-[#666] font-normal mb-[12rpx]">规格：
                        <text class="mr-[10rpx]" v-for="(it, el) in item.productList" :key="el">{{ it }}</text>
                    </view>
                    <view class="flex  items-center mb-[20rpx]">
                        <view v-for="(it, el) in item.feature" :key="el"
                            class="text-[18rpx] text-[#FF4D1B] font-normal border-[1rpx] border-[#ccc] rounded-[4rpx] mr-[8rpx]">
                            {{ it }}</view>
                    </view>
                    <view class="flex justify-between items-center">
                        <priceNumber :price="item.price"></priceNumber>
                        <view class="text-[28rpx] text-[#333] font-normal">×{{ item.num }}</view>
                    </view>
                </view>
            </view>
            <view class="flex justify-between items-center my-[32rpx]">
                <view class="text-[26rpx] font-normal text-[#333]">配送</view>
                <view class="text-[26rpx text-[#333] font-normal">顺丰快递</view>
            </view>
            <view class="flex justify-between items-center">
                <view class="text-[26rpx] text-[#333] font-normal">备注</view>
                <view>
                    <up-input placeholder="建议备注前先与商家沟通确认" border="none" v-model="value" @change="change"></up-input>
                </view>
            </view>
        </view>
        <view class="m-[20rpx] p-[32rpx] bg-[#fff] rounded-[16rpx]">
            <view class="flex justify-between items-center mb-[32rpx]">
                <view class="text-[26rpx] text-[#333] font-normal">商品金额</view>
                <view class="text-[26rpx] text-[#333] font-bold">￥{{ Detail.totalPrice }}</view>
            </view>
            <view class="flex justify-between items-center mb-[64rpx]">
                <view class="text-[26rpx] text-[#333] font-normal">配送金额</view>
                <view class="text-[26rpx] text-[#333] font-bold">￥{{ Detail.deliveryAmount }}</view>
            </view>
            <view class="flex justify-end items-center">
                <view>共 {{ countAll }} 件，合计:</view>
                <priceNumber :price="Number(Detail.payPrice) + Number(Detail.deliveryAmount ? Detail.deliveryAmount : 0)"></priceNumber>
            </view>
        </view>
        <view
            class="box-border flex px-[32rpx] py-[12rpx] pb-[30rpx] bg-[#fff] justify-between w-[100%] fixed bottom-0 left-0">
            <view class="flex items-center">
                <view class="text-[26rpx] text-[#999999] font-normal">共{{ countAll }}件，</view>
                <view class="text-[26rpx] text-[#333333] font-normal">合计：</view>
                <priceNumber :price="Number(Detail.payPrice) + Number(Detail.deliveryAmount ? Detail.deliveryAmount : 0)"></priceNumber>
            </view>
            <view @click="Submit"
                class="text-[32rpx] text-[#FFF] font-normal px-[38rpx] py-[16rpx] bg-[#FF4D1B] rounded-[80rpx]">提交订单
            </view>
        </view>
    </view>
</template>

<script setup>
import env from '@/config/common.js'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { computed, ref } from 'vue';
import priceNumber from '@/components/priceNumber'
import { GetOrderCat, GetOrderCreate, GetOrderGoods, GetOrderPay } from '../../API/order';
const { priceAll , shopShow , CheckTabA , current , checkType , distributionList , Detail, getAddress, address, countAll, Submit, ProductionOrder, callPhone, daohang } = useDetail()
const { goback, gohome } = useTable()
let value = ref('')
let baseUrl = env.API_BASE_URL_DEV
function useTable() {
    const goback = () => {
        uni.navigateBack()
    }
    const gohome = () => {
        uni.switchTab({
            url: '/pages/index/index'
        })
    }
    return { goback, gohome }
}
function useDetail() {
    let Detail = ref({})
    let address = ref({})
    let type = ref(0)
    let current = ref(0)
    let shopShow = ref(false)
    let distributionList = ref([
    {
            name:'用户自提',
            disable:false,
            check:true,
            type:0
        },
        {
            name:'快递邮寄',
            disable:false,
            check:false,
            type:1
        },{
            name:'骑手配送',
            disable:false,
            check:false,
            type:2
        }
    ])
    const countAll = computed(() => {
        let value = 0
        Detail.value.carVoList.reduce((pre,item)=>{
            return value += item.num
        },0)
        return Number(value)
    })
    const priceAll = computed(()=>{
        let price = 0
        price = Number(Detail.value.payPrice)+Number(Detail.value.discountPrice ? Detail.value.discountPrice : 0)
        return Number(price)
    })
    const getAddress = () => {
        uni.navigateTo({
            url: '/community/addressList/addressList'
        })
    }
    const ProductionOrder = async () => {
        let { data } = await GetOrderCreate()
        await orderPay(data.id)
    }
    const orderPay = async (orderId) => {
        let { data } = await GetOrderPay(orderId)
        uni.requestPayment({
            'timeStamp': data.timeStamp,
            'nonceStr': data.nonceStr,
            'package': data.packageValue,
            'signType': data.signType,
            'paySign': data.paySign,
            success: (res) => {
                console.log(res);
                uni.showToast({
                    title: '购买成功',
                    icon: 'none',
                    success: () => {
                        uni.navigateTo({
                            url: 'pageOrder/order/order'
                        })
                    }
                })
            },
            fail: (err) => {
                console.log(err);
                uni.showToast({
                    title: err.msg,
                    icon: 'none'
                })
            }
        })
        console.log(data);
    }
    const Submit = async () => {
        if (Detail.value.orderId) {
            await orderPay(Detail.value.orderId)
        } else {
            await ProductionOrder()
        }
    }
    const callPhone = () => {
        uni.makePhoneCall({
            phoneNumber: Detail.value.appStore.mobile //仅为示例，并非真实的电话号码
        })
    }
    const daohang = () => {
        uni.openLocation({
            latitude: Detail.value.appStore.lat,
            longitude: Detail.value.appStore.lng,
            name: Detail.value.appStore.name,
            address: Detail.value.appStore.address,
            success: function (res) {
                console.log('位置名称：' + res.name);
                console.log('详细地址：' + res.address);
            }
        })
    }
    const checkType =  (item,index)=>{
        if(item.disable){
            return
        }
        distributionList.value = distributionList.value.map(item=>{
            item.check = false
            return item
        })
        distributionList.value[index].check = true
        type.value = item.type
         updataOrder(type.value)
    }
    const CheckTabA = (index)=>{
        current.value = index
    }
    const updataOrder = (type)=>{
        if(shopShow.value){
            GetOrderCat({deliveryType:type}).then(res=>{
                Detail.value = res.data
                Detail.value.carVoList = Detail.value.carVoList.map(item => {
                    item.pic = baseUrl + item.pic
                    return item
                })
                distributionList.value = distributionList.value.map((item,index)=>{
                    if(Detail.value.canDeliveryType.filter(it=>it == index).length > 0){
                        item.disable = false
                    }else{
                        item.disable = true
                    }
                    return item
                })
            })
        }else{
            GetOrderGoods({
                productId: Detail.value.carVoList[0].productId,
			    num: Detail.value.carVoList[0].num,
			    deliveryType: type,
            }).then(res=>{
                console.log(res);
                Detail.value = res.data
                Detail.value.carVoList = Detail.value.carVoList.map(item => {
                    item.pic = baseUrl + item.pic
                    return item
                })
                distributionList.value = distributionList.value.map((item,index)=>{
                    if(Detail.value.canDeliveryType.filter(it=>it == index).length > 0){
                        item.disable = false
                    }else{
                        item.disable = true
                    }
                    return item
                })
            })
        }
    }
    return { priceAll,  shopShow , CheckTabA , current , checkType ,distributionList , Detail, getAddress, address, countAll, ProductionOrder, Submit, callPhone, daohang }
}
onLoad((options) => {
    if (options.item) {
        console.log(JSON.parse(options.item));
        shopShow.value = options.shopShow
        Detail.value = JSON.parse(options.item)
        Detail.value.carVoList = Detail.value.carVoList.map(item => {
            item.pic = baseUrl + item.pic
            return item
        })
        distributionList.value = distributionList.value.map((item,index)=>{
            console.log(Detail.value.canDeliveryType.filter(it=>it == index).length > 0);
            if(Detail.value.canDeliveryType.filter(it=>it == index).length > 0){
                item.disable = false
            }else{
                item.disable = true
            }
            return item
        })
    }
    if (options.order) {
        console.log(JSON.parse(options.order));
        Detail.value = {
            ...JSON.parse(options.order),
            carVoList: []
        }
        Detail.value.carVoList = Detail.value.orderPageVoList.map(item => {
            item.pic = baseUrl + item.pic
            return item
        })
    }
})
onReady(() => {
    uni.$on('address', (res) => {
        Detail.value.address = res.address
        Detail.value.province = res.province
        Detail.value.city = res.city
        Detail.value.area = res.area
        Detail.value.receiveName = res.receiveName
        Detail.value.mobile = res.province
        Detail.value.addressId = res.id
        console.log(res);
    })
})
</script>

<style lang="scss" scoped>
.addressBox {
    padding: 24rpx;
    border-radius: 16rpx;
    background: linear-gradient(90deg, #F0F2F5 0%, #FFFFFF 100%);

    .tab {
        width: 56rpx;
        height: 32rpx;
        background: linear-gradient(90deg, #FF9200 0%, #FF4200 100%);
        border-radius: 4rpx 4rpx 4rpx 4rpx;
        font-weight: 400;
        font-size: 20rpx;
        color: #FFFFFF;
        text-align: center;
        line-height: 32rpx;
    }
}
</style>